import json
import os

class I18n:
    def __init__(self, language='ru'):
        self.language = language
        self.translations = self.load_translations()

    def load_translations(self):
        base_dir = os.path.dirname(os.path.abspath(__file__))
        # Simplified path construction
        filepath = os.path.join(base_dir, '..', 'translations', f'{self.language}.json')

        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            if self.language != 'ru':
                self.language = 'ru' # Fallback to Russian
                return self.load_translations()
            return {}

    def translate(self, key, **kwargs):
        return self.translations.get(key, key).format(**kwargs)

def get_current_language():
    # In a real app, this might read from a config file
    # For now, we can assume a default or a simple file-based setting
    try:
        with open("language.settings", "r") as f:
            return f.read().strip()
    except FileNotFoundError:
        return 'ru'

i18n = I18n(get_current_language())

TRANSLATIONS = {
    "ru": {
        "app_title": "Laitoxx",
        "search": "Поиск",
        "add_step": "Добавить шаг",
        "remove_step": "Удалить шаг",
        "run_script": "Запустить скрипт",
        "save_script": "Сохранить скрипт",
        "load_script": "Загрузить скрипт",
        "step": "Шаг",
        "function": "Функция",
        "input_from": "Входные данные из",
        "previous_step": "Предыдущий шаг",
        "user_input": "Пользовательский ввод",
        "input_data": "Входные данные",
        "output_parsing": "Парсинг вывода",
        "regex_for_parsing": "REGEX для парсинга",
        "api_key": "API-ключ",
        "settings": "Настройки",
        "settings_window_title": "Настройки",
        "sw_nav_general": "Общие",
        "sw_nav_themes": "Темы",
        "sw_nav_background": "Фон",
        "sw_nav_proxy": "Прокси",
        "sw_open_site_on_startup": "Открывать сайт проекта при запуске",
        "sw_language": "Язык",
        "sw_select_theme": "Выберите тему",
        "sw_apply_theme": "Применить тему",
        "sw_open_theme_editor": "Открыть редактор темы",
        "sw_theme_name_title": "Имя темы",
        "sw_theme_name_prompt": "Введите название темы",
        "sw_select_bg": "Выберите фон",
        "sw_apply_bg": "Применить фон",
        "sw_import_bg": "Импортировать фон",
        "sw_import_bg_dialog": "Выберите файл фона",
        "sw_proxy_enable": "Включить прокси",
        "sw_proxy_type": "Тип",
        "sw_proxy_host": "Хост",
        "sw_proxy_port": "Порт",
        "sw_proxy_username": "Логин",
        "sw_proxy_password": "Пароль",
        "sw_proxy_user_placeholder": "логин (если нужен)",
        "sw_proxy_pass_placeholder": "пароль (если нужен)",
        "sw_proxy_save": "Сохранить прокси",
        "sw_proxy_saved_title": "Прокси",
        "sw_proxy_saved_msg": "Настройки прокси сохранены",
        "theme_name_title": "Имя темы",
        "theme_name_prompt": "Введите название темы",
        "language": "Язык",
        "theme": "Тема",
        "save": "Сохранить",
        "script_saved": "Скрипт сохранен",
        "script_loaded": "Скрипт загружен",
        "error": "Ошибка",
        "select_script": "Выберите скрипт для загрузки",
        "enter_script_name": "Введите имя файла для сохранени��",
        "no_function_selected": "Функция не выбрана",
        "input_data_required": "Необходимо ввести входные данные",
        "step_error": "Ошибка на шаге {step_num}: {error}",
        "script_completed": "Скрипт выполнен",
        "script_failed": "Скрипт не выполнен",
        "no_steps": "Нет шагов для выполнения",
        "invalid_json": "Неверный формат JSON файла",
        "select_file": "Выберите файл",
        "file_not_found": "Файл не найден",
        "add_regex": "Добавить REGEX",
        "remove_regex": "Удалить REGEX",
        "change_background": "Изменить фон",
        "change_theme": "Изменить тему",
        "create_color_theme": "Создать цветовую тему",
        "plugin_builder": "Конструктор плагинов",
        "hide_ui": "Скрыть интерфейс",
        "show_ui": "Показать интерфейс",
        "exit": "Выход",
        "information_gathering": "Сбор информации",
        "web_security": "Веб-безопасность",
        "utils": "Утилиты",
        "hashing": "Утилиты",
        "plugins": "Плагины",
        "Check Phone Number": "Проверить номер телефона",
        "Check IP": "Проверить IP",
        "Validate Email": "Проверить Email",
        "Data Search": "Поиск данных",
        "Info Website": "Информация о сайте",
        "Gmail Osint": "Gmail Osint",
        "Database search": "Поиск по базам данных",
        "Check MAC-address": "Проверить MAC-адрес",
        "Subdomain finder": "Поиск субдоменов",
        "Google Osint": "Google Osint",
        "Telegram (paketlib)": "Telegram (paketlib)",
        "Search Nick": "Поиск по нику",
        "Web-crawler": "Веб-краулер",
        "Port Scanner": "Сканер портов",
        "HTTP Inspector": "HTTP Инспектор",
        "Tech Detector": "Детектор технологий",
        "CMS Audit": "Аудит CMS",
        "data_search_title": "Поиск данных",
        "data_search_mode_label": "Тип поиска",
        "data_search_value_label": "Введите значение",
        "data_search_phone_option": "Телефон",
        "data_search_email_option": "Email",
        "data_search_telegram_option": "Telegram",
        "data_search_phone_placeholder": "Введите номер без +",
        "data_search_email_placeholder": "Введите email",
        "data_search_telegram_placeholder": "Введите username без @",
        "plugin_builder_title": "Конструктор плагинов",
        "plugin_name": "Имя плагина",
        "author_name": "Имя автора",
        "website": "Веб-сайт",
        "description": "Описание",
        "supported_os": "Поддерживаемые ОС",
        "continue": "Продолжить",
        "cancel": "Отмена",
        "add_delay": "Добавить задержку",
        "delete_last_step": "Удалить последний шаг",
        "save_plugin": "Сохранить плагин",
        "editing_plugin": "Редактирование: {name}",
        "set_delay_title": "Установить задержку",
        "delay_seconds": "Задержка (секунды)",
        "step_settings_title": "Настройки шага",
        "select_icon": "Выбрать иконку",
        "step_description": "Описание шага",
        "input_source": "Источник ввода",
        "input_source_user": "Пользовательск��й ввод",
        "input_source_none": "Ничего",
        "input_source_previous": "Из: {description}",
        "input_filter_regex": "Фильтр ввода (REGEX)",
        "action_type": "Тип действия",
        "action_type_command": "Командная строка",
        "action_type_function": "Внутренняя функция",
        "action_value": "Действие",
        "requires_api_key": "Требуется API-ключ",
        "plugin_name_label": "Имя плагина:",
        "author_name_label": "Имя автора:",
        "website_label": "Веб-сайт (необязательно):",
        "description_label": "Описание:",
        "step_description_default": "...",
        "delay_duration_seconds": "{duration}с",
        "step_default_name": "Шаг {order}",
        "new_step_default_description": "Новый шаг",
        "image_files_filter": "Файлы изображений (*.png *.jpg)",
        "graph_editor": "Редактор графов",
        "graph_editor_title": "Редактор графов и связей",
        "ge_new": "Новый", "ge_open": "Открыть", "ge_save": "Сохранить",
        "ge_save_as": "Сохранить как", "ge_add_node": "+ Узел", "ge_add_edge": "+ Связь",
        "ge_delete": "Удалить", "ge_export": "Экспорт",
        "ge_direction_label": "Напр.:", "ge_name_label": "Имя:",
        "ge_panels_opacity": "Панели",
        "ge_section_nodes": "УЗЛЫ", "ge_section_edges": "СВЯЗИ",
        "ge_section_preview": "ПРЕДПРОСМОТР", "ge_section_properties": "СВОЙСТВА",
        "ge_mermaid_code_label": "Mermaid Код",
        "ge_status_ready": "Готов",
        "ge_node_count": "{n} узл.", "ge_edge_count": "{n} связей",
        "ge_new_graph_name": "Новый граф",
        "ge_new_graph_confirm": "Отбросить текущий граф и создать новый?",
        "ge_new_graph_created": "Новый граф создан.",
        "ge_opened": "Открыт: {name}", "ge_saved": "Сохранён: {name}",
        "ge_error_open": "Ошибка открытия:\n{err}",
        "ge_error_save": "Ошибка сохранения:\n{err}",
        "ge_error_invalid_edge": "Неверный узел источника или цели.",
        "ge_need_2_nodes": "Нужно минимум 2 узла для создания связи.",
        "ge_node_added": "Узел добавлен: {label}", "ge_node_updated": "Узел обновлён: {label}",
        "ge_node_deleted": "Удалён: {label}", "ge_node_cloned": "Клонирован: {label}",
        "ge_edge_added": "Связь: {src} → {tgt}",
        "ge_edge_updated": "Связь обновлена: {id}", "ge_edge_deleted": "Связь удалена: {id}",
        "ge_dialog_add_node": "Добавить узел",
        "ge_dialog_edit_node": "Изменить узел — {label}",
        "ge_dialog_add_edge": "Добавить связь",
        "ge_dialog_edit_edge": "Изменить связь — {id}",
        "ge_dialog_mermaid_title": "Mermaid Код",
        "ge_field_label": "Метка:", "ge_field_type": "Тип:", "ge_field_shape": "Форма:",
        "ge_field_description": "Описание:", "ge_field_source": "Источник:",
        "ge_field_target": "Цель:", "ge_field_line": "Линия:",
        "ge_visual_style": "Визуальный стиль", "ge_metadata": "Метаданные",
        "ge_meta_add": "+ Добавить", "ge_meta_remove": "− Удалить",
        "ge_style_fill": "Заливка", "ge_style_line": "Линия", "ge_style_text": "Текст",
        "ge_style_width": "Толщина", "ge_style_dash": "Пунктир",
        "ge_dash_solid": "Сплошной", "ge_dash_dashed": "Пунктир", "ge_dash_dotted": "Точечный",
        "ge_prop_node": "СВОЙСТВА УЗЛА", "ge_prop_edge": "СВОЙСТВА СВЯЗИ",
        "ge_prop_edit": "Изменить",
        "ge_prop_id": "ID", "ge_prop_label": "Метка", "ge_prop_type": "Тип",
        "ge_prop_shape": "Форма", "ge_prop_description": "Описание",
        "ge_prop_meta": "Мета", "ge_prop_source": "Источник",
        "ge_prop_target": "Цель", "ge_prop_line": "Линия",
        "ge_ctx_edit": "✏  Изменить…", "ge_ctx_clone": "⊕  Клонировать",
        "ge_ctx_delete": "✕  Удалить",
        "ge_ctx_run_action": "▶  Действие…",
        "ge_ctx_copy_value": "📋  Копировать значение",
        "ge_act_dialog_title": "Действие для узла",
        "ge_act_value": "Значение",
        "ge_act_value_placeholder": "Введите значение…",
        "ge_act_choose": "Выберите действие",
        "ge_act_plugins": "Плагины",
        "ge_act_run": "Запустить",
        "ge_act_check_phone": "Проверить телефон",
        "ge_act_check_email": "Проверить Email",
        "ge_act_gmail_osint": "Gmail OSINT",
        "ge_act_check_ip": "Проверить IP",
        "ge_act_info_website": "Информация о сайте",
        "ge_act_find_subdomains": "Поиск субдоменов",
        "ge_act_search_nick": "Поиск по нику",
        "ge_act_data_search": "Поиск данных",
        "lua_builder_title": "Конструктор Lua плагинов",
        "lua_check_syntax": "Проверить синтаксис",
        "lua_insert_snippet": "Вставить блок",
        "lua_open_file": "Открыть файл",
        "ge_no_web_engine": "Установите PyQt6-WebEngine для отображения графа\npip install PyQt6-WebEngine",
        "ge_label_placeholder": "Метка узла…",
        "ge_edge_label_placeholder": "Метка связи…",
        "ge_desc_placeholder": "Описание (необязательно)…",
        "ge_name_placeholder": "Название графа…",
        "ge_delete_node_title": "Удалить узел",
        "ge_delete_node_confirm": "Удалить узел '{label}' и все его связи?",
        "ge_copy_suffix": " (копия)",
        "ge_d3_zoom": "Scroll", "ge_d3_zoom_hint": "масштаб",
        "ge_d3_drag": "Drag", "ge_d3_drag_hint": "перемещение",
        "ge_d3_hover": "Hover", "ge_d3_hover_hint": "детали узла",
        "ge_d3_connections": "Связей",
        "ge_d3_nodes_count": "узл.", "ge_d3_edges_count": "связей",
        "ge_node_type_person": "Персона", "ge_node_type_email": "Email",
        "ge_node_type_phone": "Телефон", "ge_node_type_website": "Сайт",
        "ge_node_type_company": "Компания", "ge_node_type_ip": "IP-адрес",
        "ge_node_type_address": "Адрес", "ge_node_type_document": "Документ",
        "ge_node_type_custom": "Пользовательский",
        "ge_shape_rect": "Прямоугольник", "ge_shape_round": "Скруглённый",
        "ge_shape_circle": "Круг", "ge_shape_diamond": "Ромб",
        "ge_shape_hexagon": "Шестиугольник", "ge_shape_flag": "Флаг",
        "ge_shape_trapez": "Трапеция",
        "ge_edge_type_connected": "Связан", "ge_edge_type_worksfor": "Работает в",
        "ge_edge_type_owns": "Владеет", "ge_edge_type_relatedto": "Связан с",
        "ge_edge_type_communicates": "Общается", "ge_edge_type_locatedat": "Находится в",
        "ge_edge_type_memberof": "Участник", "ge_edge_type_custom": "Пользовательский",
        "ge_line_arrow": "Стрелка →", "ge_line_thick": "Жирная ⟹",
        "ge_line_dotted": "Пунктир →", "ge_line_open": "Без стрелки —",
        "ge_line_open_dotted": "Пунктир без стрелки", "ge_line_double": "Двойная ↔",
        "theme_map": {
            "button_bg_color": "Фон кнопки",
            "button_hover_bg_color": "Фон кнопки при наведении",
            "button_pressed_bg_color": "Фон кнопки при нажатии",
            "button_border_color": "Цвет рамки кнопки",
            "button_text_color": "Цвет текста кнопки",
            "text_area_bg_color": "Фон текстовой области",
            "text_area_border_color": "Цвет рамки текстовой области",
            "text_area_text_color": "Цвет текста текстовой области",
            "sidebar_bg_color": "Фон боковой панели",
            "title_text_color": "Цвет заголовка",
            "scrollbar_handle_color": "Цвет ползунка прокрутки",
            "scrollbar_handle_hover_color": "Цвет ползунка прокрутки при наведении",
            "plugin_canvas_bg_color": "Фон холста плагина"
        },
        "search": "Поиск..."
    },
    "en": {
        "app_title": "Laitoxx",
        "search": "Search...",
        "add_step": "Add Step",
        "remove_step": "Remove Step",
        "run_script": "Run Script",
        "save_script": "Save Script",
        "load_script": "Load Script",
        "step": "Step",
        "function": "Function",
        "input_from": "Input from",
        "previous_step": "Previous Step",
        "user_input": "User Input",
        "input_data": "Input Data",
        "output_parsing": "Output Parsing",
        "regex_for_parsing": "REGEX for parsing",
        "api_key": "API Key",
        "settings": "Settings",
        "settings_window_title": "Settings",
        "sw_nav_general": "General",
        "sw_nav_themes": "Themes",
        "sw_nav_background": "Background",
        "sw_nav_proxy": "Proxy",
        "sw_open_site_on_startup": "Open project site on startup",
        "sw_language": "Language",
        "sw_select_theme": "Select theme",
        "sw_apply_theme": "Apply theme",
        "sw_open_theme_editor": "Open theme editor",
        "sw_theme_name_title": "Theme Name",
        "sw_theme_name_prompt": "Enter theme name",
        "sw_select_bg": "Select background",
        "sw_apply_bg": "Apply background",
        "sw_import_bg": "Import background",
        "sw_import_bg_dialog": "Select background file",
        "sw_proxy_enable": "Enable proxy",
        "sw_proxy_type": "Type",
        "sw_proxy_host": "Host",
        "sw_proxy_port": "Port",
        "sw_proxy_username": "Username",
        "sw_proxy_password": "Password",
        "sw_proxy_user_placeholder": "username (optional)",
        "sw_proxy_pass_placeholder": "password (optional)",
        "sw_proxy_save": "Save proxy",
        "sw_proxy_saved_title": "Proxy",
        "sw_proxy_saved_msg": "Proxy settings saved",
        "theme_name_title": "Theme Name",
        "theme_name_prompt": "Enter theme name",
        "language": "Language",
        "theme": "Theme",
        "save": "Save",
        "script_saved": "Script saved",
        "script_loaded": "Script loaded",
        "error": "Error",
        "select_script": "Select a script to load",
        "enter_script_name": "Enter a filename to save",
        "no_function_selected": "No function selected",
        "input_data_required": "Input data is required",
        "step_error": "Error at step {step_num}: {error}",
        "script_completed": "Script completed",
        "script_failed": "Script failed",
        "no_steps": "No steps to run",
        "invalid_json": "Invalid JSON file format",
        "select_file": "Select file",
        "file_not_found": "File not found",
        "add_regex": "Add REGEX",
        "remove_regex": "Remove REGEX",
        "change_background": "Change Background",
        "change_theme": "Change Theme",
        "create_color_theme": "Create Color Theme",
        "plugin_builder": "Plugin Builder",
        "hide_ui": "Hide UI",
        "show_ui": "Show UI",
        "exit": "Exit",
        "information_gathering": "Information Gathering",
        "web_security": "Web Security",
        "utils": "Utils",
        "hashing": "Utils",
        "plugins": "Plugins",
        "Check Phone Number": "Check Phone Number",
        "Check IP": "Check IP",
        "Validate Email": "Validate Email",
        "Data Search": "Data Search",
        "Info Website": "Info Website",
        "Gmail Osint": "Gmail Osint",
        "Database search": "Database search",
        "Check MAC-address": "Check MAC-address",
        "Subdomain finder": "Subdomain finder",
        "Google Osint": "Google Osint",
        "Telegram (paketlib)": "Telegram (paketlib)",
        "Search Nick": "Search Nick",
        "Web-crawler": "Web-crawler",
        "Port Scanner": "Port Scanner",
        "HTTP Inspector": "HTTP Inspector",
        "Tech Detector": "Tech Detector",
        "CMS Audit": "CMS Audit",
        "data_search_title": "Data Search",
        "data_search_mode_label": "Search type",
        "data_search_value_label": "Enter value",
        "data_search_phone_option": "Phone",
        "data_search_email_option": "Email",
        "data_search_telegram_option": "Telegram",
        "data_search_phone_placeholder": "Phone without +",
        "data_search_email_placeholder": "Enter email",
        "data_search_telegram_placeholder": "Username without @",
        "plugin_builder_title": "Plugin Builder",
        "plugin_name": "Plugin Name",
        "author_name": "Author Name",
        "website": "Website",
        "description": "Description",
        "supported_os": "Supported OS",
        "continue": "Continue",
        "cancel": "Cancel",
        "add_delay": "Add Delay",
        "delete_last_step": "Delete Last Step",
        "save_plugin": "Save Plugin",
        "editing_plugin": "Editing: {name}",
        "set_delay_title": "Set Delay",
        "delay_seconds": "Delay (seconds)",
        "step_settings_title": "Step Settings",
        "select_icon": "Select Icon",
        "step_description": "Step Description",
        "input_source": "Input Source",
        "input_source_user": "User Input",
        "input_source_none": "None",
        "input_source_previous": "From: {description}",
        "input_filter_regex": "Input Filter (REGEX)",
        "action_type": "Action Type",
        "action_type_command": "Command Line",
        "action_type_function": "Internal Function",
        "action_value": "Action",
        "requires_api_key": "Requires API Key",
        "plugin_name_label": "Plugin Name:",
        "author_name_label": "Author Name:",
        "website_label": "Website (optional):",
        "description_label": "Description:",
        "step_description_default": "...",
        "delay_duration_seconds": "{duration}s",
        "step_default_name": "Step {order}",
        "new_step_default_description": "New Step",
        "image_files_filter": "Image Files (*.png *.jpg)",
        "graph_editor": "Graph Editor",
        "graph_editor_title": "Graph & Link Editor",
        "ge_new": "New", "ge_open": "Open", "ge_save": "Save",
        "ge_save_as": "Save As", "ge_add_node": "+ Node", "ge_add_edge": "+ Edge",
        "ge_delete": "Delete", "ge_export": "Export",
        "ge_direction_label": "Dir:", "ge_name_label": "Name:",
        "ge_panels_opacity": "Panels",
        "ge_section_nodes": "NODES", "ge_section_edges": "EDGES",
        "ge_section_preview": "GRAPH PREVIEW", "ge_section_properties": "PROPERTIES",
        "ge_mermaid_code_label": "Mermaid Code",
        "ge_status_ready": "Ready",
        "ge_node_count": "{n} nodes", "ge_edge_count": "{n} edges",
        "ge_new_graph_name": "New Graph",
        "ge_new_graph_confirm": "Discard current graph and create a new one?",
        "ge_new_graph_created": "New graph created.",
        "ge_opened": "Opened: {name}", "ge_saved": "Saved: {name}",
        "ge_error_open": "Failed to open graph:\n{err}",
        "ge_error_save": "Failed to save:\n{err}",
        "ge_error_invalid_edge": "Invalid source or target node.",
        "ge_need_2_nodes": "Need at least 2 nodes to create an edge.",
        "ge_node_added": "Node added: {label}", "ge_node_updated": "Node updated: {label}",
        "ge_node_deleted": "Deleted: {label}", "ge_node_cloned": "Cloned: {label}",
        "ge_edge_added": "Edge: {src} → {tgt}",
        "ge_edge_updated": "Edge updated: {id}", "ge_edge_deleted": "Deleted edge: {id}",
        "ge_dialog_add_node": "Add Node",
        "ge_dialog_edit_node": "Edit Node — {label}",
        "ge_dialog_add_edge": "Add Edge",
        "ge_dialog_edit_edge": "Edit Edge — {id}",
        "ge_dialog_mermaid_title": "Mermaid Code",
        "ge_field_label": "Label:", "ge_field_type": "Type:", "ge_field_shape": "Shape:",
        "ge_field_description": "Description:", "ge_field_source": "Source:",
        "ge_field_target": "Target:", "ge_field_line": "Line:",
        "ge_visual_style": "Visual Style", "ge_metadata": "Metadata",
        "ge_meta_add": "+ Add", "ge_meta_remove": "− Remove",
        "ge_style_fill": "Fill", "ge_style_line": "Line", "ge_style_text": "Text",
        "ge_style_width": "Width", "ge_style_dash": "Dash",
        "ge_dash_solid": "Solid", "ge_dash_dashed": "Dashed", "ge_dash_dotted": "Dotted",
        "ge_prop_node": "NODE PROPERTIES", "ge_prop_edge": "EDGE PROPERTIES",
        "ge_prop_edit": "Edit",
        "ge_prop_id": "ID", "ge_prop_label": "Label", "ge_prop_type": "Type",
        "ge_prop_shape": "Shape", "ge_prop_description": "Description",
        "ge_prop_meta": "Meta", "ge_prop_source": "Source",
        "ge_prop_target": "Target", "ge_prop_line": "Line",
        "ge_ctx_edit": "✏  Edit…", "ge_ctx_clone": "⊕  Clone",
        "ge_ctx_delete": "✕  Delete",
        "ge_ctx_run_action": "▶  Run Action…",
        "ge_ctx_copy_value": "📋  Copy Value",
        "ge_act_dialog_title": "Node Action",
        "ge_act_value": "Value",
        "ge_act_value_placeholder": "Enter value…",
        "ge_act_choose": "Choose an action",
        "ge_act_plugins": "Plugins",
        "ge_act_run": "Run",
        "ge_act_check_phone": "Check Phone",
        "ge_act_check_email": "Check Email",
        "ge_act_gmail_osint": "Gmail OSINT",
        "ge_act_check_ip": "Check IP",
        "ge_act_info_website": "Website Info",
        "ge_act_find_subdomains": "Find Subdomains",
        "ge_act_search_nick": "Search Nick",
        "ge_act_data_search": "Data Search",
        "lua_builder_title": "Lua Plugin Builder",
        "lua_check_syntax": "Check Syntax",
        "lua_insert_snippet": "Insert Snippet",
        "lua_open_file": "Open File",
        "ge_no_web_engine": "Install PyQt6-WebEngine for live graph rendering\npip install PyQt6-WebEngine",
        "ge_label_placeholder": "Node label…",
        "ge_edge_label_placeholder": "Relationship label…",
        "ge_desc_placeholder": "Optional description…",
        "ge_name_placeholder": "Graph name…",
        "ge_delete_node_title": "Delete Node",
        "ge_delete_node_confirm": "Delete node '{label}' and all its edges?",
        "ge_copy_suffix": " (copy)",
        "ge_d3_zoom": "Scroll", "ge_d3_zoom_hint": "zoom",
        "ge_d3_drag": "Drag", "ge_d3_drag_hint": "move",
        "ge_d3_hover": "Hover", "ge_d3_hover_hint": "node details",
        "ge_d3_connections": "Connections",
        "ge_d3_nodes_count": "nodes", "ge_d3_edges_count": "edges",
        "ge_node_type_person": "Person", "ge_node_type_email": "Email",
        "ge_node_type_phone": "Phone", "ge_node_type_website": "Website",
        "ge_node_type_company": "Company", "ge_node_type_ip": "IP",
        "ge_node_type_address": "Address", "ge_node_type_document": "Document",
        "ge_node_type_custom": "Custom",
        "ge_shape_rect": "Rectangle", "ge_shape_round": "Rounded",
        "ge_shape_circle": "Circle", "ge_shape_diamond": "Diamond",
        "ge_shape_hexagon": "Hexagon", "ge_shape_flag": "Flag",
        "ge_shape_trapez": "Trapezoid",
        "ge_edge_type_connected": "Connected", "ge_edge_type_worksfor": "Works For",
        "ge_edge_type_owns": "Owns", "ge_edge_type_relatedto": "Related To",
        "ge_edge_type_communicates": "Communicates", "ge_edge_type_locatedat": "Located At",
        "ge_edge_type_memberof": "Member Of", "ge_edge_type_custom": "Custom",
        "ge_line_arrow": "Arrow →", "ge_line_thick": "Thick Arrow ⟹",
        "ge_line_dotted": "Dotted →", "ge_line_open": "Open —",
        "ge_line_open_dotted": "Open Dotted", "ge_line_double": "Double ↔",
        "theme_map": {
            "button_bg_color": "Button Background",
            "button_hover_bg_color": "Button Hover",
            "button_pressed_bg_color": "Button Pressed",
            "button_border_color": "Button Border",
            "button_text_color": "Button Text",
            "text_area_bg_color": "Text Area Background",
            "text_area_border_color": "Text Area Border",
            "text_area_text_color": "Text Area Text",
            "sidebar_bg_color": "Sidebar Background",
            "title_text_color": "Title Text",
            "scrollbar_handle_color": "Scrollbar Handle",
            "scrollbar_handle_hover_color": "Scrollbar Handle Hover",
            "plugin_canvas_bg_color": "Plugin Canvas Background"
        }
    }
}

# Ensure the translations directory and files exist
base_dir = os.path.dirname(os.path.abspath(__file__))
translations_dir = os.path.join(base_dir, '..', 'translations')
os.makedirs(translations_dir, exist_ok=True)

for lang, trans_data in TRANSLATIONS.items():
    filepath = os.path.join(translations_dir, f'{lang}.json')
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(trans_data, f, ensure_ascii=False, indent=4)
